from pyecharts.charts import Bar, Timeline
from pyecharts import options as opts
from pyecharts.globals import ThemeType
import pandas as pd



def process_data(df):
    """处理数据"""
    grouped_df = df.groupby(['年份', '月份', '车型'])['销量'].sum().reset_index()
    return grouped_df

def car_sales_visualization(df):
    # 处理数据
    grouped_df = process_data(df)
    
    # 创建Timeline对象
    timeline = Timeline()
    
    # 初始化累计销量DataFrame和颜色映射
    cumulative_sales = pd.DataFrame(columns=['车型', '累计销量'])
    all_models = grouped_df['车型'].unique()
    colors = [
        "#c23531", "#2f4554", "#61a0a8", "#d48265", "#91c7ae",
        "#749f83", "#ca8622", "#bda29a", "#6e7074", "#546570",
        "#c4ccd3", "#f05b72", "#ef5b9c", "#f47920", "#905a3d"
    ]
    color_map = {model: colors[i % len(colors)] for i, model in enumerate(all_models)}
    
    # 生成动态图表
    for (year, month), group in grouped_df.groupby(['年份', '月份']):
        # 计算累计销量
        current_month_sales = group[['车型', '销量']].rename(columns={'销量': '累计销量'})
        cumulative_sales = pd.concat([cumulative_sales, current_month_sales]).groupby('车型')['累计销量'].sum().reset_index()
        
        # 获取top 15
        cumulative_sales['排名'] = cumulative_sales['累计销量'].rank(ascending=False, method='dense')
        top_15 = cumulative_sales.nsmallest(15, '排名')
        current_colors = [color_map[model] for model in top_15['车型']]
        
        # 创建柱状图
        bar = (
            Bar()
            .add_xaxis(top_15['车型'].tolist())
            .add_yaxis(
                "销量",
                top_15['累计销量'].tolist(),
                itemstyle_opts=[{"color": color} for color in current_colors]
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(
                    title=f"{year}年{month}月车型累计销量排行",
                    subtitle="自2015年起"
                ),
                xaxis_opts=opts.AxisOpts(name="车型", axislabel_opts=opts.LabelOpts(rotate=45)),
                yaxis_opts=opts.AxisOpts(name="销量"),
                toolbox_opts=opts.ToolboxOpts(is_show=False),
                legend_opts=opts.LegendOpts(pos_top="5%")
            )
        )
        
        timeline.add(bar, time_point=f"{year}年{month}月")
    
    # 设置Timeline选项
    timeline.add_schema(
        play_interval=1000,
        is_auto_play=True,
        is_loop_play=True,
        is_timeline_show=False,
        label_opts=opts.LabelOpts(is_show=False)
    )
    
    return timeline.render_embed()
